'use strict';

const Controller = require('egg').Controller;

class UserInfoController extends Controller {

  async addUserInfo() {
    // 获取前端传来的参数
    const { ctx } = this;
    ctx.body = ctx.request.body;
    let retrunMap = {};
    let transaction;
    const user_id = ctx.body.user_id;
    try {

      // 建立事务对象
      transaction = await this.ctx.model.transaction();

      // 处理
      const userInfo = await this.ctx.service.userInfoService.addUserInfo(ctx.body, transaction);
      console.log(userInfo);
      const userRelation = {
        user_id,
        info_id: userInfo.id,
        relation: ctx.body.relation,
      };
      const users = await this.ctx.service.userRelationService.addUserInfo(userRelation, transaction);
      // 提交事务
      await transaction.commit();
      if (users) {
        retrunMap = { code: '1', msg: '添加成功', data: users };
      } else {
        retrunMap = { code: '0', msg: '添加失败' };
      }
    } catch (err) {
      retrunMap = { code: '0', msg: '添加失败' };
      console.log(err);
      // 事务回滚
      await transaction.rollback();
    }
    // 返回
    ctx.body = retrunMap;
  }
  /**
 * 获取关联的父母信息
 */
  async getUserInfoList() {
    const { ctx } = this;
    const user_id = ctx.params.id;
    let retrunMap = {};
    try {
      const userInfos = await this.ctx.service.userInfoService.getUserInfoList(user_id);
      retrunMap = { code: '1', msg: '查询成功', data: userInfos };
    } catch (error) {
      retrunMap = { code: '0', msg: '查询失败' };
      console.log(error);
    }

    ctx.body = retrunMap;

  }

}

module.exports = UserInfoController;
